<template>
    <view class="page flex-col">
        <view class="group_1 flex-row">
            <view class="box_1 flex-col">
                <view class="text-group_1 flex-col">
                    <text class="text_2">请扫描身份证的正反面</text>
                    <text class="text_3">正面为头像面&nbsp;反面为国徽面</text>
                </view>
                <view class="list_1 flex-col">
                    <view class="list-items_1 flex-row justify-between" v-for="(item, index) in loopData0" :key="index">
                        <view class="text-group_2 flex-col">
                            <text class="text_4">{{ item.lanhutext0 }}</text>
                            <text class="text_5">{{ item.lanhutext1 }}</text>
                        </view>
                        <image class="idcard-img" :src="item.lanhuBg2" @click="uploadIdCard(item, index)"></image>
                    </view>
                </view>
            </view>
            <view class="box_2 flex-col">
                <text class="text_6">请确认实名信息</text>
                <view class="text-wrapper_1 ">
                    <view class="userinfo-item flex-row">
                        <text class="paragraph_1">姓名：</text>
                        <text class="paragraph_2">{{ ocrResult.realName || '待识别' }}</text>
                    </view>
                    <view class="userinfo-item flex-row">
                        <text class="paragraph_1">性别：</text>
                        <text class="paragraph_2">{{ ocrResult.sex || '待识别' }}</text>
                    </view>
                    <view class="userinfo-item flex-row">
                        <text class="paragraph_1">身份证号：</text>
                        <text class="paragraph_2">{{ ocrResult.cardNumber || '待识别' }}</text>
                    </view>
                </view>
                <view class="group_3 flex-row justify-between">
                    <view class="text-wrapper_2 flex-col" @click="reUpload">
                        <text class="text_7">信息不对？</text>
                    </view>
                    <view class="text-wrapper_3 flex-col" @click="confirmInfo">
                        <text class="text_8">确认无误</text>
                    </view>
                </view>
            </view>
        </view>
        <!-- 信息有误弹窗 -->
        <view class="popup-mask" v-if="showInfoErrorPopup">
            <view class="group_1 flex-col">
                <view class="text-wrapper_1 flex-row">
                    <text class="text_1">信息有误？</text>
                </view>
                <view class="block_1 flex-row justify-between">
                    <text class="paragraph_1">
                        可能原因：
                        <br />
                        您上传的身份证照片模糊导致识别不清
                        <br />
                        <br />
                        请确保：
                        <br />
                        ●&nbsp;照片清晰、无反光、无遮挡。
                        <br />
                        ●&nbsp;身份证四个边角完整显示。
                        <br />
                        ●&nbsp;在光线充足的环境下拍摄。
                        <br />
                        <br />
                        请尝试重新拍照上传~
                    </text>
                </view>
                <view class="block_2 flex-row justify-between">
                    <view class="text-wrapper_2 flex-col" @click="reAuthenticate">
                        <text class="text_2">重新认证</text>
                    </view>
                    <view class="text-wrapper_3 flex-col" @click="closePopup">
                        <text class="text_3">暂不认证</text>
                    </view>
                </view>
            </view>
        </view>
    </view>
</template>
<script>
const app_info = require("@/common/appInfo.js");
const api_host = app_info.api_host;
import { registerUser, updateUser } from '@/common/api_meethuangshi.js'
export default {
    data() {
        return {
            loopData0: [
                {
                    type: 'Front',
                    lanhutext0: '头像面',
                    lanhutext1: '上传您的身份证头像面',
                    lanhuBg2: 'https://hxs.dsjhs.com:553/prod-api/profile/sfz-z.png',
                },
                {
                    type: 'Back',
                    lanhutext0: '国徽面',
                    lanhutext1: '上传您的身份证国徽面',
                    lanhuBg2: 'https://hxs.dsjhs.com:553/prod-api/profile/sfz-f.png',
                },
            ],
            constants: {},
            // 添加OCR识别结果数据
            ocrResult: {
                name: '',
                gender: '',
                cardNumber: ''
            },
            // 添加上传状态
            uploading: false,
            // 保存上传的文件路径
            uploadedFiles: {
                Front: null,  // 正面文件路径
                Back: null     // 反面文件路径
            },
            // 新增：保存识别成功状态
            ocrStatus: {
                Front: false,  // 正面识别状态
                Back: false    // 反面识别状态
            },
            showInfoErrorPopup: false,
            isUpdate: false,
            currentUser: {}
        };
    },
    async onLoad(options) {
        this.isUpdate = options.isUpdate == 'true'
        this.currentUser = await this.ensureUserInfo();
    },
    methods: {
        // 根据出生日期字符串计算实际年龄（支持 1998-12-5 / 1998-12-05 / 1998/12/5 / 19981205）
        computeAge(birthStr) {
            if (!birthStr || typeof birthStr !== 'string') return 0;
            const raw = birthStr.trim();
            let year = 0, month = 0, day = 0;

            if (/^\d{8}$/.test(raw)) {
                year = parseInt(raw.substr(0, 4), 10);
                month = parseInt(raw.substr(4, 2), 10);
                day = parseInt(raw.substr(6, 2), 10);
            } else {
                const parts = raw.replace(/\//g, '-').split('-').filter(Boolean);
                if (parts.length < 3) return 0;
                year = parseInt(parts[0], 10);
                month = parseInt(parts[1], 10);
                day = parseInt(parts[2], 10);
            }

            if (!year || !month || !day) return 0;
            const birthDate = new Date(year, month - 1, day);
            if (Number.isNaN(birthDate.getTime())) return 0;

            const today = new Date();
            let age = today.getFullYear() - year;
            const monthDiff = today.getMonth() - (month - 1);
            const dayDiff = today.getDate() - day;
            if (monthDiff < 0 || (monthDiff === 0 && dayDiff < 0)) {
                age -= 1;
            }
            return age < 0 ? 0 : age;
        },
        // 上传单张身份证进行OCR识别
        uploadSingleFileForOCR(filePath, type) {
            return new Promise((resolve, reject) => {
                // 使用真正的multipart/form-data文件上传
                this.uploadSingleRealFormData(filePath, type).then(resolve).catch(reject);
            });
        },

        // 单张文件的multipart/form-data上传
        uploadSingleRealFormData(filePath, type) {
            return new Promise((resolve, reject) => {
                // #ifdef H5
                // H5环境下使用原生FormData和fetch
                this.getFileFromPath(filePath).then(file => {
                    const formData = new FormData();
                    formData.append('file', file, `${type.toLowerCase()}.jpg`);
                    formData.append('type', type); // Front 或 Back

                    fetch(api_host + '/wx/idCardOCR', {
                        method: 'POST',
                        body: formData
                    }).then(response => response.json())
                        .then(data => {
                            if (data.code == 200) {
                                resolve(data);
                            } else {
                                resolve(data);
                                uni.showModal({
                                    title: '提示',
                                    content: data.msg,
                                    showCancel: false
                                });
                            }
                        })
                        .catch(reject);
                }).catch(reject);
                // #endif

                // #ifdef APP-PLUS || MP-WEIXIN
                // 小程序和App环境下的单文件上传
                uni.uploadFile({
                    url: api_host + '/wx/idCardOCR',
                    filePath: filePath,
                    name: 'file',
                    formData: {
                        type: type // Front 或 Back
                    },
                    success: (res) => {
                        let data = JSON.parse(res.data);
                        if (data.code == 200) {
                            resolve(data);
                        } else {
                            resolve(data);
                            uni.showModal({
                                title: '提示',
                                content: data.msg,
                                showCancel: false
                            });
                        }
                    },
                    fail: reject,
                    complete: () => {
                        uni.hideLoading();
                    }
                });
                // #endif
            });
        },

        async uploadIdCard(item, index) {
            // 身份证图片选择
            uni.chooseImage({
                count: 1,
                sourceType: ['album', 'camera'],
                success: async (res) => {
                    try {
                        console.log(res, 'uploadIdCard');

                        // 保存文件路径
                        this.uploadedFiles[item.type] = res.tempFilePaths[0];

                        // 更新界面显示的图片
                        this.loopData0[index].lanhuBg2 = res.tempFilePaths[0];

                        // 根据上传的是正面还是反面给出不同提示
                        const tipText = item.type === 'Front' ? '身份证正面上传成功' : '身份证反面上传成功';
                        uni.showToast({
                            title: tipText,
                            icon: 'none',
                            duration: 1500
                        });

                        // 立即开始OCR识别
                        setTimeout(async () => {
                            await this.performSingleOCR(res.tempFilePaths[0], item.type);
                        }, 800);

                    } catch (error) {
                        console.error('图片选择失败:', error);
                        uni.showToast({
                            title: '取消先择图片',
                            icon: 'none',
                            duration: 3000
                        });
                    }
                },
                fail: (err) => {
                    console.log('选择图片失败:', err);
                    uni.showToast({
                        title: '取消先择图片',
                        icon: 'none',
                        duration: 2000
                    });
                }
            });
        },

        // 执行单张图片OCR识别
        async performSingleOCR(filePath, type) {
            try {
                this.uploading = true;
                uni.showLoading({
                    title: '正在识别身份中',
                    mask: true
                });

                // 调用单张OCR识别接口
                const ocrRes = await this.uploadSingleFileForOCR(filePath, type);

                console.log(ocrRes, `${type} OCR结果:`, ocrRes);

                if (ocrRes.code === 200) {
                    // 只有正面（Front）才更新OCR识别结果
                    if (type === 'Front' && ocrRes.data) {
                        this.ocrResult = {
                            realName: ocrRes.data.name || '',
                            sex: ocrRes.data.gender || '',
                            cardNumber: ocrRes.data.id || '',
                            birth: ocrRes.data.birth || '',
                        };
                    }
                    // 更新对应面的识别状态为成功
                    this.ocrStatus[type] = true;

                    const successText = type === 'Front' ? '正面识别成功！' : '反面识别成功！';
                    uni.showToast({
                        title: successText,
                        icon: 'none',
                        duration: 2000
                    });
                } else {
                    // 识别失败时设置状态为false
                    this.ocrStatus[type] = false;
                    throw new Error(ocrRes.msg || '身份信息识别失败');
                }

            } catch (error) {
                console.error(`${type}身份证识别失败:`, error);
                // 识别失败时设置状态为false
                this.ocrStatus[type] = false;
                uni.showToast({
                    title: error.message || '识别失败，请检查照片清晰度后重试',
                    icon: 'none',
                    duration: 3000
                });
            } finally {
                this.uploading = false;
                uni.hideLoading();
            }
        },

        // H5环境下从文件路径获取File对象
        getFileFromPath(filePath) {
            return new Promise((resolve, reject) => {
                // #ifdef H5
                fetch(filePath)
                    .then(response => response.blob())
                    .then(blob => {
                        const file = new File([blob], 'idcard.jpg', { type: 'image/jpeg' });
                        resolve(file);
                    })
                    .catch(reject);
                // #endif

                // #ifdef APP-PLUS || MP-WEIXIN
                // 非H5环境直接返回文件路径
                resolve(filePath);
                // #endif
            });
        },

        // 确认信息无误
        async confirmInfo() {
            // 检查是否完成身份证信息识别
            if (!this.ocrResult.realName || !this.ocrResult.cardNumber) {
                uni.showToast({
                    title: '请先完成身份证正面上传和识别',
                    icon: 'none',
                    duration: 2500
                });
                return;
            }

            // 检查正反面是否都识别成功
            if (!this.ocrStatus.Front || !this.ocrStatus.Back) {
                let missingText = '';
                if (!this.ocrStatus.Front && !this.ocrStatus.Back) {
                    missingText = '请先完成身份证正反面识别';
                } else if (!this.ocrStatus.Front) {
                    missingText = '请先完成身份证正面识别';
                } else if (!this.ocrStatus.Back) {
                    missingText = '请先完成身份证反面识别';
                }

                uni.showToast({
                    title: missingText,
                    icon: 'none',
                    duration: 2500
                });
                return;
            }

            // 这里可以跳转到下一步或提交数据
            console.log('确认的身份信息:', this.ocrResult);
            console.log('识别状态:', this.ocrStatus);
            uni.showToast({
                title: '身份信息确认成功！',
                icon: 'none',
                duration: 2000
            });

            const personInfoData = uni.getStorageSync('personInfoData') || {}
            personInfoData.sex = this.ocrResult.sex
            personInfoData.realName = this.ocrResult.realName
            personInfoData.cardNumber = this.ocrResult.cardNumber
            personInfoData.year = this.computeAge(this.ocrResult.birth)
            personInfoData.idCert = 2
            personInfoData.userId = this.currentUser.id
            const requestApi = this.isUpdate ? updateUser : registerUser
            console.log(requestApi, personInfoData, 'requestApi')
            const res = await requestApi(personInfoData)
            console.log(res, 'res')
            if (res.code === 200) {
                uni.setStorageSync('personInfoData', personInfoData)
                uni.navigateTo({
                    url: '/subpage/meethuangshi/index?showSkip=true'
                });
            }

            // if (this.isUpdate) {
            //     console.log(uni.getStorageSync('personInfoData'), 'isUpdate')
            //     const updateParams = {
            //         idCert: 2,
            //         userId: uni.getStorageSync('personInfoData').userId,
            //         ...this.ocrResult
            //     }
            //     const res = await updateUser(updateParams)
            //     if (res.code === 200) {
            //         uni.navigateTo({
            //             url: '/subpage/meethuangshi/index?showSkip=true'
            //         });
            //     }
            // } else {
            //     const personInfoData = uni.getStorageSync('personInfoData') || {}
            //     personInfoData.sex = this.ocrResult.sex
            //     personInfoData.realName = this.ocrResult.realName
            //     personInfoData.cardNumber = this.ocrResult.cardNumber
            //     personInfoData.year = this.computeAge(this.ocrResult.birth)
            //     console.log(this.ocrResult, personInfoData.year, 'personInfoData.year')
            //     personInfoData.idCert = 2
            //     uni.setStorageSync('personInfoData', personInfoData)
            //     const res = await registerUser(personInfoData)
            //     console.log(res, 'res')
            //     if (res.code === 200) {
            //         uni.navigateTo({
            //             url: '/subpage/meethuangshi/index?showSkip=true'
            //         });
            //     }
            // }


        },

        // 信息不对，重新识别
        reUpload() {
            this.showInfoErrorPopup = true;
        },

        reAuthenticate() {
            this.showInfoErrorPopup = false;
            // 清空OCR识别结果
            this.ocrResult = {
                name: '',
                gender: '',
                cardNumber: ''
            };
            // 清空上传的文件路径
            this.uploadedFiles = {
                Front: null,
                Back: null
            };
            // 重置识别状态
            this.ocrStatus = {
                Front: false,
                Back: false
            };
            // 重置图片为默认状态
            this.loopData0[0].lanhuBg2 = 'https://hxs.dsjhs.com:553/prod-api/profile/sfz-z.png';
            this.loopData0[1].lanhuBg2 = 'https://hxs.dsjhs.com:553/prod-api/profile/sfz-f.png';

            uni.showToast({
                title: '已重置，请重新上传身份证正反面',
                icon: 'none',
                duration: 2500
            });
        },
        async closePopup() {
            this.showInfoErrorPopup = false;
            const res = await registerUser(uni.getStorageSync('personInfoData'))
            console.log(res, 'res')
            if (res.code === 200) {
                uni.navigateTo({
                    url: '/subpage/meethuangshi/index?showSkip=true'
                });
            }
        }
    },
};
</script>
<style lang="scss" scoped>
@import '../../static/style/common.css';

.page {
    background-color: rgba(247, 246, 255, 1);
    position: relative;
    width: 390px;
    height: 844px;
    overflow: hidden;

    .group_1 {
        .box_1 {
            padding: 18px 6px 0 0;

            .group_2 {
                margin: 0 27px 0 43px;

                .text_1 {
                    overflow-wrap: break-word;
                    color: rgba(0, 0, 0, 1);
                    font-size: 17px;
                    font-family: SFPro-Semibold;
                    font-weight: 600;
                    text-align: right;
                    white-space: nowrap;
                    line-height: 22px;
                }

                .thumbnail_1 {
                    width: 19px;
                    height: 12px;
                    margin: 5px 0 5px 182px;
                }

                .thumbnail_2 {
                    width: 17px;
                    height: 12px;
                    margin: 5px 0 5px 8px;
                }

                .image_1 {
                    width: 27px;
                    height: 13px;
                    margin: 5px 0 4px 7px;
                }
            }

            .image_2 {
                width: 384px;
                height: 46px;
                margin-top: 6px;
            }

            .text-group_1 {
                margin: 16px 188px 0 16px;

                .text_2 {
                    overflow-wrap: break-word;
                    color: rgba(52, 49, 79, 1);
                    font-size: 18px;
                    font-family: PingFangSC-Medium;
                    font-weight: 500;
                    text-align: left;
                    white-space: nowrap;
                    line-height: 25px;
                }

                .text_3 {
                    overflow-wrap: break-word;
                    color: rgba(52, 49, 79, 1);
                    font-size: 14px;
                    font-weight: normal;
                    text-align: left;
                    white-space: nowrap;
                    line-height: 20px;
                    margin: 4px 7px 0 0;
                }
            }

            .list_1 {
                height: 372px;
                margin: 12px 10px 0 16px;

                .list-items_1 {
                    background-color: rgba(255, 255, 255, 1);
                    border-radius: 20px;
                    width: 358px;
                    margin-bottom: 12px;
                    padding: 34px 16px 35px 16px;

                    .text-group_2 {
                        margin: 28px 0 29px 0;

                        .text_4 {
                            overflow-wrap: break-word;
                            color: rgba(52, 49, 79, 1);
                            font-size: 20px;
                            font-family: PingFangSC-Medium;
                            font-weight: 500;
                            text-align: left;
                            white-space: nowrap;
                            line-height: 28px;
                            margin-right: 80px;
                        }

                        .text_5 {
                            overflow-wrap: break-word;
                            color: rgba(52, 49, 79, 1);
                            font-size: 14px;
                            font-weight: normal;
                            text-align: left;
                            white-space: nowrap;
                            line-height: 20px;
                            margin-top: 6px;
                        }
                    }

                    .idcard-img {
                        width: 170px;
                        height: 111px;
                        border-radius: 12px;

                    }
                }
            }
        }

        .box_2 {
            position: fixed;
            bottom: 0;
            left: 0;
            background-color: rgba(255, 255, 255, 1);
            border-radius: 20px 20px 0px 0px;
            padding: 20px 16px 28px 16px;

            .text_6 {
                overflow-wrap: break-word;
                color: rgba(52, 49, 79, 1);
                font-size: 18px;
                font-family: PingFangSC-Medium;
                font-weight: 500;
                text-align: left;
                white-space: nowrap;
                line-height: 25px;
                margin: 0 224px 0 8px;
            }

            .text-wrapper_1 {
                margin: 16px 0 0 8px;

                .paragraph_1 {
                    width: 80px;
                    overflow-wrap: break-word;
                    color: rgba(52, 49, 79, 1);
                    font-size: 16px;
                    font-family: PingFangSC-Medium;
                    font-weight: 500;
                    text-align: left;
                    line-height: 32px;
                }

                .paragraph_2 {
                    width: 170px;
                    overflow-wrap: break-word;
                    color: rgba(52, 49, 79, 1);
                    font-size: 16px;
                    font-weight: normal;
                    text-align: left;
                    line-height: 32px;
                }
            }

            .group_3 {
                width: 358px;
                margin: 36px auto 0;

                .text-wrapper_2 {
                    width: 134px;
                    height: 48px;
                    background: rgba(52, 49, 79, 0.06);
                    border-radius: 20px;
                    text-align: center;


                    .text_7 {
                        overflow-wrap: break-word;
                        color: rgba(52, 49, 79, 1);
                        font-size: 16px;
                        font-family: PingFangSC-Semibold;
                        font-weight: 600;
                        white-space: nowrap;
                        line-height: 48px;
                    }
                }

                .text-wrapper_3 {
                    width: 210px;
                    height: 48px;
                    background: linear-gradient(173deg, #FFA5F5 0%, #319EFF 100%);
                    border-radius: 20px;
                    text-align: center;

                    .text_8 {
                        overflow-wrap: break-word;
                        color: rgba(255, 255, 255, 1);
                        font-size: 16px;
                        font-family: PingFangSC-Semibold;
                        font-weight: 600;
                        text-align: center;
                        white-space: nowrap;
                        line-height: 48px;
                    }
                }
            }
        }
    }

    .popup-mask {
        position: fixed;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0, 0, 0, 0.5);
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 999;

        .group_1 {
            background-color: rgba(255, 255, 255, 1);
            border-radius: 20px;
            padding: 32px 6px 28px 16px;
            margin: 20px;
            max-width: 90%;
            max-height: 80%;

            .text-wrapper_1 {
                width: 90px;
                align-self: center;

                .text_1 {
                    overflow-wrap: break-word;
                    color: rgba(52, 49, 79, 1);
                    font-size: 18px;
                    font-family: PingFangSC-Medium;
                    font-weight: 500;
                    text-align: center;
                    white-space: nowrap;
                    line-height: 25px;
                }
            }

            .block_1 {
                width: 294px;
                margin-top: 28px;

                .paragraph_1 {
                    width: 238px;
                    height: 180px;
                    overflow-wrap: break-word;
                    color: rgba(52, 49, 79, 1);
                    font-size: 14px;
                    font-weight: normal;
                    text-align: left;
                    line-height: 20px;
                }

                .box_1 {
                    background-color: rgba(233, 233, 233, 1);
                    border-radius: 2px;
                    width: 4px;
                    height: 84px;
                    margin: 35px 0 61px 0;
                }
            }

            .block_2 {
                width: 284px;
                margin: 28px 10px 0 0;

                .text-wrapper_2 {
                    background-color: rgba(52, 49, 79, 0.06);
                    border-radius: 20px;
                    padding: 13px 35px 13px 35px;

                    .text_2 {
                        overflow-wrap: break-word;
                        color: rgba(52, 49, 79, 1);
                        font-size: 16px;
                        font-family: PingFangSC-Semibold;
                        font-weight: 600;
                        text-align: center;
                        white-space: nowrap;
                        line-height: 22px;
                    }
                }

                .text-wrapper_3 {
                    background: linear-gradient(173deg, #FFA5F5 0%, #319EFF 100%);
                    padding: 13px 35px 13px 35px;
                    border-radius: 20px;

                    .text_3 {
                        overflow-wrap: break-word;
                        color: rgba(255, 255, 255, 1);
                        font-size: 16px;
                        font-family: PingFangSC-Semibold;
                        font-weight: 600;
                        text-align: center;
                        white-space: nowrap;
                        line-height: 22px;
                    }
                }
            }
        }
    }
}
</style>